//
//  DateExtension.swift
//  Intersection
//
//  Created by 我骑着蜗牛走天下 on 2025/2/25.
//

import Foundation


/// 日期格式枚举（支持扩展）
public enum DateFormat: CustomStringConvertible {
    // MARK: - 标准格式
    /// 完整时间戳 (示例: 2023-09-15 14:30:45)
    case fullDateTime
    /// 日期+小时分钟 (示例: 2023-09-15 14:30)
    case dateHourMinute
    /// 纯日期格式 (示例: 2023-09-15)
    case dateOnly
    /// 月份+日期 (示例: 09-15)
    case monthDay
    /// 月份名称+日期 (示例: September 15)
    case monthNameDay
    /// 年份+月份 (示例: 2023-09)
    case yearMonth
    /// 点分隔的年月日
    case pointYearMonthDay
    /// ISO8601 格式 (示例: 2023-09-15T14:30:45Z)
    case iso8601
    
    // MARK: - 自定义格式
    /// 自定义分隔符的日期 (参数示例: separator: "/" → 2023/09/15)
    case customDate(separator: String)
    /// 完全自定义格式字符串 (参数示例: "yyyy/MM/dd HH:mm:ss")
    case custom(String)
    
    // 通过 description 返回格式字符串
    public var description: String {
        switch self {
        // 标准格式
        case .fullDateTime: return "yyyy-MM-dd HH:mm:ss"
        case .dateHourMinute: return "yyyy-MM-dd HH:mm"
        case .dateOnly: return "yyyy-MM-dd"
        case .monthDay: return "MM-dd"
        case .monthNameDay: return "MMMM d"
        case .yearMonth: return "yyyy-MM"
        case .pointYearMonthDay: return "yyyy.MM.dd"
        case .iso8601: return "yyyy-MM-dd'T'HH:mm:ssZ"
            
        // 自定义格式
        case .customDate(let separator):
            return separator
        case .custom(let format):
            return format
        }
    }
}




extension Date {
    
    /// 获取秒级时间戳
    public var timestamp: Int64 {
        return Int64(self.timeIntervalSince1970)
    }
    
    /// 获取毫秒级时间戳（扩展知识）
    public var timestampMilliseconds: Int64 {
        return Int64(self.timeIntervalSince1970 * 1000)
    }
    
    /// 使用指定格式和可选时区、locale，从字符串创建 Date 实例
    /// - Parameters:
    ///   - string: 要转换的日期字符串
    ///   - format: 日期格式，如 "MM_dd_HH_mm"
    ///   - timeZone: 时区，默认当前时区
    ///   - locale: 区域设置，默认 en_US_POSIX，保证解析稳定
    /// - Returns: 转换成功的 Date，失败返回 nil
    static func from(_ string: String,
                     format: String,
                     timeZone: TimeZone = .current,
                     locale: Locale = Locale(identifier: "en_US_POSIX")) -> Date? {
        let formatter = DateFormatter()
        formatter.dateFormat = format
        formatter.timeZone = timeZone
        formatter.locale = locale
        return formatter.date(from: string)
    }
    
    ///Date转字符串
    public func toString(dateFormat:DateFormat = .fullDateTime) -> String {
        let formatter = DateFormatter()
        formatter.timeZone = TimeZone.current
        formatter.locale = Locale.init(identifier: "zh_CN")
        formatter.dateFormat = dateFormat.description
        let date = formatter.string(from: self)
        return date//.components(separatedBy: " ").first!
    }
    
    /// 计算和今天的天数差
    public func daysDifferenceIgnoringTime() -> Int {
        let calendar = Calendar.current
        let todayStart = calendar.startOfDay(for: Date())
        let targetDateStart = calendar.startOfDay(for: self)
        return calendar.dateComponents([.day], from: targetDateStart, to: todayStart).day!
    }
    
    
    
    /// 智能格式化日期：
    /// - 1分钟内 → "刚刚"
    /// - 1小时内 → "X分钟前"
    /// - 今天内 → "X小时前"
    /// - 昨天 → "昨天 HH:mm"
    /// - 前天 → "前天 HH:mm"
    /// - 更早 → "M月d日 HH:mm"
    public func toSmartDateString() -> String {
        let calendar = Calendar.current
        let now = Date()
        
        // 计算基于零点的天数差
        let startOfToday = calendar.startOfDay(for: now)
        let startOfTargetDate = calendar.startOfDay(for: self)
        let daysAgo = calendar.dateComponents([.day], from: startOfTargetDate, to: startOfToday).day ?? 0
        
        // 计算时间差（秒）
        let timeInterval = now.timeIntervalSince(self)
        let totalMinutes = Int(timeInterval / 60)
        
        let dateFormatter = DateFormatter()
        dateFormatter.locale = Locale(identifier: "zh_CN") // 中文格式
        
        switch daysAgo {
        case 0:
            if totalMinutes < 1 {
                return "刚刚"
            } else if totalMinutes < 60 {
                return "\(totalMinutes)分钟前"
            } else {
                let hours = totalMinutes / 60
                return "\(hours)小时前"
            }
        case 1:
            dateFormatter.dateFormat = "昨天 HH:mm"
            return dateFormatter.string(from: self)
        case 2:
            dateFormatter.dateFormat = "前天 HH:mm"
            return dateFormatter.string(from: self)
        default:
            dateFormatter.dateFormat = "M月d日 HH:mm" // 如 "3月17日 09:30"
            return dateFormatter.string(from: self)
        }
    }
    
    /// 智能格式化日期：
    /// - 今天内 → "今天"
    /// - 昨天 → "昨天"
    /// - 前天 → "前天"
    /// - 更早 → "年.月.日"
    public func toSmartTwoDateString() -> String {
        let calendar = Calendar.current
        let now = Date()
        
        // 计算基于零点的天数差
        let startOfToday = calendar.startOfDay(for: now)
        let startOfTargetDate = calendar.startOfDay(for: self)
        let daysAgo = calendar.dateComponents([.day], from: startOfTargetDate, to: startOfToday).day ?? 0
        
        // 计算时间差（秒）
        let timeInterval = now.timeIntervalSince(self)
        let totalMinutes = Int(timeInterval / 60)
        
        let dateFormatter = DateFormatter()
        dateFormatter.locale = Locale(identifier: "zh_CN") // 中文格式
        
        switch daysAgo {
        case 0:
            return "今天"
        case 1:
            return "昨天"
        case 2:
            return "前天"
        default:
            return self.toString(dateFormat: .pointYearMonthDay)
        }
    }
    
    /// 返回当天的00秒
    public func strtOfDay() -> Date? {
        let calendar = Calendar.current
        // 获取当天的年、月、日
        var components = calendar.dateComponents([.year, .month, .day], from: self)
        // 设置时间为0:0:0
        components.hour = 0
        components.minute = 0
        components.second = 0
        // 生成当天最后一秒的Date
        return calendar.date(from: components)
    }
    
    /// 返回当天的最后一秒
    public func endOfDay() -> Date? {
        let calendar = Calendar.current
        // 获取当天的年、月、日
        var components = calendar.dateComponents([.year, .month, .day], from: self)
        // 设置时间为23:59:59
        components.hour = 23
        components.minute = 59
        components.second = 59
        // 生成当天最后一秒的Date
        return calendar.date(from: components)
    }
    
    
}
